package com.ddh.codeduck.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.ddhcodeduck.common.exception.BusinessException;
import com.ddhcodeduck.common.exception.ErrorCode;
import com.ddhcodeduck.common.utils.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Sa-Token 登录拦截器
 */
@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 使用 Sa-Token 校验登录状态（自动处理 Token 校验、多端登录等）
        if (!StpUtil.isLogin()) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 2. 获取当前登录用户 ID 并存入 ThreadLocal（供业务层使用）
        String userId = null;
        userId = StpUtil.getLoginIdAsString();
        UserContextHolder.setUserId(userId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求结束后清理 ThreadLocal
        UserContextHolder.clear();
    }
}
